use std::collections::HashMap;

use crate::clothing::Clothing;
use crate::tool::{Tool, ToolResult};
// 1. 库存查询工具：查询指定衣服的库存和详情
pub struct StockQueryTool {
    clothes: Vec<Clothing>, // 模拟数据库存储的商品
}

impl StockQueryTool {
    pub fn new(clothes: Vec<Clothing>) -> Self {
        StockQueryTool { clothes }
    }
}

impl Tool for StockQueryTool {
    fn name(&self) -> &str {
        "stock_query"
    }

    fn run(&self, params: &HashMap<String, serde_json::Value>) -> Result<ToolResult, String> {
        // 解析参数：商品ID或名称
        let query = params.get("query")
            .and_then(|v| v.as_str())
            .ok_or("缺少参数query（商品ID或名称）")?;

        // 搜索商品（支持ID或名称模糊匹配）
        let mut matches: Vec<&Clothing> = self.clothes.iter()
            .filter(|c| c.id == query || c.name.contains(query))
            .collect();

        if matches.is_empty() {
            //return Ok(ToolResult {
            //    success: false,
            //    content: format!("未找到商品：{}", query),
            //});
            matches = self.clothes.iter().collect();
        }

        // 格式化库存信息
        let mut content = String::new();
        for c in matches {
            content.push_str(&format!(
                "- {}（ID:{}）：颜色{}，价格¥{:.2}，库存{}件，适合{}季节\n",
                c.name,
                c.id,
                c.color.iter()
                    .map(|s| s.as_str()) 
                    .collect::<Vec<_>>()
                    .join("/"),
                c.price,
                c.stock,
                c.suitable_season.iter()
                    .map(|s| s.as_str()) 
                    .collect::<Vec<_>>()
                    .join("/")
            ));
        }

        Ok(ToolResult {
            success: true,
            content,
        })
    }
}

// 2. 搭配推荐工具：根据已选商品推荐搭配
pub struct MatchingRecommendTool {
    clothes: Vec<Clothing>,
}

impl MatchingRecommendTool {
    pub fn new(clothes: Vec<Clothing>) -> Self {
        MatchingRecommendTool { clothes }
    }
}

impl Tool for MatchingRecommendTool {
    fn name(&self) -> &str {
        "matching_recommend"
    }

    fn run(&self, params: &HashMap<String, serde_json::Value>) -> Result<ToolResult, String> {
        // 解析参数：已选商品ID和季节
        let selected_id = params.get("selected_id")
            .and_then(|v| v.as_str())
            .ok_or("缺少参数selected_id（已选商品ID）")?;
        let season = params.get("season")
            .and_then(|v| v.as_str())
            .ok_or("缺少参数season（季节）")?;

        // 找到已选商品
        let selected = self.clothes.iter()
            .find(|c| c.id == selected_id)
            .ok_or(format!("未找到商品ID: {}", selected_id))?;

        // 推荐逻辑：同季节、不同品类（如上衣配裤子）
        let recommendations: Vec<&Clothing> = self.clothes.iter()
            .filter(|c| {
                c.id != selected_id // 排除自身
                && c.suitable_season.contains(season) // 同季节
                && c.category != selected.category // 不同品类
                && c.stock > 0 // 有库存
            })
            .take(3) // 最多推荐3个
            .collect();

        if recommendations.is_empty() {
            return Ok(ToolResult {
                success: false,
                content: format!("暂无与{}搭配的商品", selected.name),
            });
        }

        let mut content = format!("为您推荐与{}搭配的商品：\n", selected.name);
for c in recommendations {
    // 将颜色集合转换为用逗号分隔的字符串
    let colors = c.color.iter()
        .cloned()
        .collect::<Vec<_>>()
        .join("、");
    
    content.push_str(&format!(
        "- {}：颜色{}，价格¥{:.2}（库存{}件）\n",
        c.name, colors, c.price, c.stock
    ));
}

        Ok(ToolResult {
            success: true,
            content,
        })
    }
}

// 3. 折扣计算工具：根据购买数量和会员等级计算最终价格
pub struct DiscountCalculationTool;

impl Tool for DiscountCalculationTool {
    fn name(&self) -> &str {
        "discount_calculation"
    }

    fn run(&self, params: &HashMap<String, serde_json::Value>) -> Result<ToolResult, String> {
        // 解析参数：单价、数量、会员等级
        let price = params.get("price")
            .and_then(|v| v.as_f64())
            .ok_or("缺少参数price（单价）")?;
        let quantity = params.get("quantity")
            .and_then(|v| v.as_i64())
            .map(|v| v as i32)
            .ok_or("缺少参数quantity（数量）")?;
        let member_level = params.get("member_level")
            .and_then(|v| v.as_str())
            .ok_or("缺少参数member_level（会员等级）")?;

        // 计算折扣（会员等级越高折扣越大）
        let discount = match member_level {
            "普通" => 1.0,
            "白银" => 0.95,
            "黄金" => 0.9,
            "钻石" => 0.85,
            _ => return Err("无效的会员等级（支持：普通/白银/黄金/钻石）".to_string()),
        };

        // 满减优惠（满300减30，满500减60）
        let total = price * quantity as f64 * discount;
        let final_total = if total >= 500.0 {
            total - 60.0
        } else if total >= 300.0 {
            total - 30.0
        } else {
            total
        };

        Ok(ToolResult {
            success: true,
            content: format!(
                "原价：¥{:.2}，会员折扣（{}）：{}折，满减优惠：¥{:.2}，最终总价：¥{:.2}",
                price * quantity as f64,
                member_level,
                discount * 10.0,
                total - final_total,
                final_total
            ),
        })
    }
}
pub fn test_clothing_guide() {
    // 初始化商品数据（模拟数据库）
 let clothes_data = vec![
    Clothing {
        id: "2201".to_string(),
        name: "户外多功能三合一冲锋衣外套".to_string(),
        category: "外套".to_string(),
        price: 99.0,
        color: vec!["黑色", "蓝色"].into_iter().map(|s| s.to_string()).collect(), // 修正为颜色值
        stock: 50,
        suitable_season: vec!["春季", "秋季"].into_iter().map(|s| s.to_string()).collect(),
        size: vec!["S", "M", "L", "XL"].into_iter().map(|s| s.to_string()).collect(),
        material: vec!["聚酯纤维", "棉"].into_iter().map(|s| s.to_string()).collect(),
        brand: "户外探索".to_string(),
        description: "防风防水，适合多种户外场景".to_string(),
    },
    Clothing {
        id: "2202".to_string(),
        name: "户外多功能三合一冲锋衣外套".to_string(),
        category: "外套".to_string(),
        price: 159.0,
        color: vec!["红色", "灰色"].into_iter().map(|s| s.to_string()).collect(), // 修正为颜色值
        stock: 30,
        suitable_season: vec!["春季", "秋季", "冬季"].into_iter().map(|s| s.to_string()).collect(),
        size: vec!["M", "L", "XL", "XXL"].into_iter().map(|s| s.to_string()).collect(),
        material: vec!["尼龙", "抓绒"].into_iter().map(|s| s.to_string()).collect(),
        brand: "户外探索".to_string(),
        description: "加绒加厚，适合寒冷天气".to_string(),
    },
    Clothing {
        id: "5521".to_string(),
        name: "情侣户外冲锋衣".to_string(),
        category: "外套".to_string(),
        price: 259.0,
        color: vec!["藏青色", "卡其色"].into_iter().map(|s| s.to_string()).collect(), // 修正为颜色值
        stock: 20,
        suitable_season: vec!["秋季", "冬季"].into_iter().map(|s| s.to_string()).collect(),
        size: vec!["S", "M", "L", "XL"].into_iter().map(|s| s.to_string()).collect(),
        material: vec![" Gore-Tex", "聚酯纤维"].into_iter().map(|s| s.to_string()).collect(),
        brand: "情侣户外".to_string(),
        description: "情侣款设计，防风透气".to_string(),
    },
    Clothing {
        id: "5522".to_string(),
        name: "情侣户外冲锋衣".to_string(),
        category: "外套".to_string(),
        price: 259.0,
        color: vec!["黑色", "军绿色"].into_iter().map(|s| s.to_string()).collect(), // 修正为颜色值
        stock: 20,
        suitable_season: vec!["秋季", "冬季"].into_iter().map(|s| s.to_string()).collect(),
        size: vec!["S", "M", "L", "XL", "XXL"].into_iter().map(|s| s.to_string()).collect(),
        material: vec![" Gore-Tex", "聚酯纤维"].into_iter().map(|s| s.to_string()).collect(),
        brand: "情侣户外".to_string(),
        description: "情侣款设计，防风透气".to_string(),
    },
];
    // 初始化工具
    let stock_tool = StockQueryTool::new(clothes_data.clone());
    let recommend_tool = MatchingRecommendTool::new(clothes_data.clone());
    let discount_tool = DiscountCalculationTool;

    // 创建异步运行时（同步main调用异步工具）
    // Runtime::new().expect("创建运行时失败");

    // 模拟销售流程：查询库存 → 推荐搭配 → 计算折扣
    println!("\n===== 1. 查询T恤库存 =====");
    let mut stock_params = HashMap::new();
    stock_params.insert("query".to_string(), serde_json::Value::String("T恤".to_string()));
    let stock_result = stock_tool.run(&stock_params).unwrap();
    println!("{}", stock_result.content);

    println!("\n===== 2. 推荐T恤搭配 =====");
    let mut recommend_params = HashMap::new();
    recommend_params.insert("selected_id".to_string(), serde_json::Value::String("2201".to_string()));
    recommend_params.insert("season".to_string(), serde_json::Value::String("秋季".to_string()));
    let recommend_result = recommend_tool.run(&recommend_params).unwrap();
    println!("{}", recommend_result.content);

    println!("\n===== 3. 计算折扣价格 =====");
    let mut discount_params = HashMap::new();
    discount_params.insert("price".to_string(), serde_json::Value::Number(99.into()));
    discount_params.insert("quantity".to_string(), serde_json::Value::Number(2.into()));
    discount_params.insert("member_level".to_string(), serde_json::Value::String("黄金".to_string()));
    let discount_result = discount_tool.run(&discount_params).unwrap();
    println!("{}", discount_result.content);
}